const fs = require('fs').promises;
const path = require('path');
const { dataDir } = require('../config');

// 变量目录路径
const variablesDir = path.join(dataDir, 'variables');
const globalVariablesFile = path.join(variablesDir, 'global.json');

// 确保变量目录存在
async function ensureVariablesDir() {
  try {
    await fs.access(variablesDir);
  } catch (error) {
    if (error.code === 'ENOENT') {
      await fs.mkdir(variablesDir, { recursive: true });
    } else {
      throw error;
    }
  }
}

// 获取全局变量列表
async function getGlobalVariables() {
  await ensureVariablesDir();
  
  try {
    const data = await fs.readFile(globalVariablesFile, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    if (error.code === 'ENOENT') {
      // 如果文件不存在，返回空数组
      return [];
    }
    throw error;
  }
}

// 添加或更新全局变量
async function saveGlobalVariable(variable) {
  await ensureVariablesDir();
  
  try {
    // 获取现有变量
    let variables = await getGlobalVariables();
    
    // 查找是否存在相同名称的变量
    const index = variables.findIndex(v => v.name === variable.name);
    
    if (index !== -1) {
      // 更新已存在的变量
      variables[index] = { ...variables[index], ...variable };
    } else {
      // 添加新变量
      variables.push({
        id: `var_${Date.now()}`,
        ...variable,
        createTime: new Date().toISOString()
      });
    }
    
    await fs.writeFile(globalVariablesFile, JSON.stringify(variables, null, 2), 'utf8');
    return index !== -1 ? variables[index] : variables[variables.length - 1];
  } catch (error) {
    throw error;
  }
}

// 删除全局变量
async function deleteGlobalVariable(variableId) {
  await ensureVariablesDir();
  
  try {
    let variables = await getGlobalVariables();
    const index = variables.findIndex(v => v.id === variableId);
    
    if (index === -1) {
      return false;
    }
    
    variables.splice(index, 1);
    await fs.writeFile(globalVariablesFile, JSON.stringify(variables, null, 2), 'utf8');
    return true;
  } catch (error) {
    throw error;
  }
}

// 获取事件局部变量列表
async function getEventVariables(eventId) {
  await ensureVariablesDir();
  
  const eventVariablesFile = path.join(variablesDir, `event_${eventId}.json`);
  
  try {
    const data = await fs.readFile(eventVariablesFile, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    if (error.code === 'ENOENT') {
      // 如果文件不存在，返回空数组
      return [];
    }
    throw error;
  }
}

// 添加或更新事件局部变量
async function saveEventVariable(eventId, variable) {
  await ensureVariablesDir();
  
  const eventVariablesFile = path.join(variablesDir, `event_${eventId}.json`);
  
  try {
    // 获取现有变量
    let variables = await getEventVariables(eventId);
    
    // 查找是否存在相同名称的变量
    const index = variables.findIndex(v => v.name === variable.name);
    
    if (index !== -1) {
      // 更新已存在的变量
      variables[index] = { ...variables[index], ...variable };
    } else {
      // 添加新变量
      variables.push({
        id: `var_${Date.now()}`,
        ...variable,
        eventId,
        createTime: new Date().toISOString()
      });
    }
    
    await fs.writeFile(eventVariablesFile, JSON.stringify(variables, null, 2), 'utf8');
    return index !== -1 ? variables[index] : variables[variables.length - 1];
  } catch (error) {
    throw error;
  }
}

// 删除事件局部变量
async function deleteEventVariable(eventId, variableId) {
  await ensureVariablesDir();
  
  const eventVariablesFile = path.join(variablesDir, `event_${eventId}.json`);
  
  try {
    let variables = await getEventVariables(eventId);
    const index = variables.findIndex(v => v.id === variableId);
    
    if (index === -1) {
      return false;
    }
    
    variables.splice(index, 1);
    await fs.writeFile(eventVariablesFile, JSON.stringify(variables, null, 2), 'utf8');
    return true;
  } catch (error) {
    throw error;
  }
}

// 清空事件局部变量
async function clearEventVariables(eventId) {
  await ensureVariablesDir();
  
  const eventVariablesFile = path.join(variablesDir, `event_${eventId}.json`);
  
  try {
    await fs.writeFile(eventVariablesFile, JSON.stringify([], null, 2), 'utf8');
    return true;
  } catch (error) {
    throw error;
  }
}

// 获取事件所有可用变量（包括全局变量和局部变量）
async function getAllVariablesForEvent(eventId) {
  try {
    const globalVars = await getGlobalVariables();
    const eventVars = await getEventVariables(eventId);
    
    // 标记变量来源
    globalVars.forEach(v => v.scope = 'global');
    eventVars.forEach(v => v.scope = 'event');
    
    return [...globalVars, ...eventVars];
  } catch (error) {
    throw error;
  }
}

// 查找使用了特定变量的所有事件
async function findEventsUsingVariable(variableId, variableType, page = 1, pageSize = 10) {
  try {
    // 获取指定变量
    let variable;
    if (variableType === 'global') {
      const globalVars = await getGlobalVariables();
      variable = globalVars.find(v => v.id === variableId);
    } else if (variableType === 'event') {
      // 对于事件局部变量，需要从所有事件变量中查找
      const variablesDir = path.join(dataDir, 'variables');
      const files = await fs.readdir(variablesDir);
      
      for (const file of files) {
        if (file.startsWith('event_') && file.endsWith('.json')) {
          const eventId = file.replace('event_', '').replace('.json', '');
          const eventVars = await getEventVariables(eventId);
          variable = eventVars.find(v => v.id === variableId);
          if (variable) {
            variable.eventId = eventId;
            break;
          }
        }
      }
    }
    
    if (!variable) {
      return { events: [], total: 0 };
    }
    
    // 获取所有事件
    const eventsDir = path.join(dataDir, 'events');
    const eventFiles = await fs.readdir(eventsDir);
    
    const allEvents = [];
    const variableName = variable.name;
    
    // 检查变量在事件中的使用情况
    for (const file of eventFiles) {
      if (file.endsWith('.json')) {
        const eventContent = await fs.readFile(path.join(eventsDir, file), 'utf8');
        const event = JSON.parse(eventContent);
        
        // 检查事件内容中是否引用了变量
        // 首先将事件转换为字符串进行检查
        const eventStr = JSON.stringify(event);
        
        // 对于全局变量，检查${变量名}的引用
        // 对于事件局部变量，只检查当前事件
        if (
          (variableType === 'global' && eventStr.includes(`\${${variableName}}`) || 
          (variableType === 'event' && event.id === variable.eventId && eventStr.includes(`\${${variableName}}`)))
        ) {
          // 获取事件分类信息
          const category = await getCategoryById(event.categoryId);
          
          allEvents.push({
            id: event.id,
            name: event.name,
            category: category ? category.name : '未分类',
            createTime: event.createTime || '未知'
          });
        }
      }
    }
    
    // 计算分页
    const startIndex = (page - 1) * pageSize;
    const paginatedEvents = allEvents.slice(startIndex, startIndex + pageSize);
    
    return {
      events: paginatedEvents,
      total: allEvents.length
    };
  } catch (error) {
    throw error;
  }
}

// 获取分类信息
async function getCategoryById(categoryId) {
  try {
    const categoriesFile = path.join(dataDir, 'categories.json');
    const fileExists = await fileExists(categoriesFile);
    
    if (!fileExists) {
      return null;
    }
    
    const categoriesContent = await fs.readFile(categoriesFile, 'utf8');
    const categories = JSON.parse(categoriesContent);
    
    return categories.find(c => c.id === categoryId) || null;
  } catch (error) {
    return null;
  }
}

// 检查文件是否存在的辅助函数
async function fileExists(filePath) {
  try {
    await fs.access(filePath);
    return true;
  } catch {
    return false;
  }
}

module.exports = {
  getGlobalVariables,
  saveGlobalVariable,
  deleteGlobalVariable,
  getEventVariables,
  saveEventVariable,
  deleteEventVariable,
  clearEventVariables,
  getAllVariablesForEvent,
  findEventsUsingVariable
}; 